<template>
  <div class="content">
    <student-menu />
    <main class="ml-64 flex-1 p-6 bg-gray-50 min-h-screen">
      <header class="flex justify-between items-center mb-6">
        <h1 class="text-2xl font-bold text-gray-800">岗位信息管理（前端分页）</h1>
        <div class="flex space-x-4">
          <el-button icon="el-icon-refresh" type="default" size="mini" @click="refreshData">刷新数据</el-button>
          <el-button icon="el-icon-message" type="default" size="mini" @click="contactCompany">联系单位</el-button>
        </div>
      </header>

      <!-- 筛选条件 -->
      <el-card class="mb-6" shadow="never">
        <el-form inline>
          <el-form-item label="岗位名称">
            <el-input v-model="filterParams.GWMC" clearable placeholder="请输入岗位名称" @input="applyFilters" />
          </el-form-item>
          <el-form-item label="推荐时间">
            <el-date-picker
                v-model="filterParams.TJSJ"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="applyFilters"
            />
          </el-form-item>
          <el-form-item label="推荐人">
            <el-select v-model="filterParams.TJR" clearable placeholder="请选择推荐人" @change="applyFilters" style="width: 180px;">
              <el-option
                  v-for="person in TJR_OPTIONS"
                  :key="person"
                  :label="person"
                  :value="person"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-checkbox v-model="filterParams.SFTJ" @change="applyFilters">仅显示推荐</el-checkbox>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="applyFilters">查询</el-button>
            <el-button @click="resetFilters">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 数据表格 -->
      <el-table
          :data="paginatedData"
          border
          stripe
          style="width: 100%"
          v-loading="loading"
          element-loading-background="rgba(255,255,255,0.8)"
          element-loading-spinner="el-icon-loading"
      >
        <el-table-column type="expand">
          <template #default="{ row }">
            <div class="expand-content p-4 text-gray-700">
              <p><strong>岗位描述：</strong>{{ row.GWMS }}</p>
              <p><strong>岗位要求：</strong>{{ row.GWYQ }}</p>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="GWMC" label="岗位名称" width="180" />
        <el-table-column prop="DWMC" label="单位名称" width="150" />
        <el-table-column prop="GSMC" label="公司名称" width="150" />
        <el-table-column prop="TJRXM" label="推荐人" width="120" />
        <el-table-column label="薪资范围" width="150">
          <template #default="{ row }">￥{{ row.ZDXZ }} - {{ row.ZGXZ }}</template>
        </el-table-column>
        <el-table-column prop="GZDD" label="工作地点" width="120" />
        <el-table-column label="学历要求" prop="XLMC" width="120" />
        <el-table-column label="专业要求" prop="ZYXZ" width="120" />
        <el-table-column prop="TJSJ" label="推荐时间" width="180">
          <template #default="{ row }">{{ formatDate(row.TJSJ) }}</template>
        </el-table-column>
        <el-table-column label="推荐指数" width="160">
          <template #default="{ row }">
            <el-rate v-model="row.TJDJ" disabled :colors="['#99A9BF','#F7BA2A','#FF9900']" />
          </template>
        </el-table-column>
        <el-table-column label="推荐" width="220">
          <template #default="{ row }">
            <el-button size="mini"  type="success" icon="el-icon-check" @click="handleRecommend(row)">收到确认</el-button>
            <el-button
                size="mini"
                type="warning"
                icon="el-icon-star-on"
                @click="handleShouCang(row)">
              收藏
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="mt-4 flex justify-end">
        <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :total="filteredData.length"
            layout="total, prev, pager, next"
            @current-change="handlePageChange"
        />
      </div>
    </main>
  </div>
</template>

<script>
import StudentMenu from '@/components/student/Student_menu.vue'
import dayjs from 'dayjs'
import axios from 'axios'
import { EventBus } from '@/event-bus'

export default {
  components: { StudentMenu },
  data() {
    return {
      allData: [], // 存放所有岗位数据
      filterParams: { GWMC: '', TJSJ: [], TJR: '', SFTJ: false },
      loading: false,
      currentPage: 1,
      pageSize: 7,
      UserInfo: { username: '' }
    }
  },
  computed: {
    // 推荐人下拉列表
    TJR_OPTIONS() {
      const names = this.allData.map(item => item.TJRXM || item.TJR).filter(n => n)
      return Array.from(new Set(names))
    },
    filteredData() {
      return this.allData.filter(item => {
        const matchName = !this.filterParams.GWMC || item.GWMC.includes(this.filterParams.GWMC)
        const matchTjr = !this.filterParams.TJR || (item.TJRXM === this.filterParams.TJR || item.TJR === this.filterParams.TJR)
        const matchRec = !this.filterParams.SFTJ || item.SFTJ === true
        let matchDate = true
        if (this.filterParams.TJSJ.length === 2) {
          const start = dayjs(this.filterParams.TJSJ[0])
          const end = dayjs(this.filterParams.TJSJ[1])
          const date = dayjs(item.TJSJ)
          matchDate = (date.isAfter(start) || date.isSame(start)) && (date.isBefore(end) || date.isSame(end))
        }
        return matchName && matchTjr && matchRec && matchDate
      })
    },
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize
      return this.filteredData.slice(start, start + this.pageSize)
    }
  },
  methods: {
    handleShouCang(row){
      console.log('收藏', row)
    },
    handleRecommend(row) {
      console.log('收到确认', row)
    },
    formatDate(date) {
      return dayjs(date).format('YYYY-MM-DD HH:mm')
    },
    getLoginUserInfo() {
      axios.get('/user/checkSession')
          .then(res => {
            if (res.data.result) {
              this.UserInfo.username = res.data.username
              this.loadPosts()
            } else {
              EventBus.$emit('show-auth-popup')
              setTimeout(() => this.$router.push({name: 'TeacherLoginView'}), 1000)
            }
          })
          .catch(() => {
            EventBus.$emit('show-auth-popup')
            setTimeout(() => this.$router.push({name: 'Login'}), 1000)
          })
    },
    loadPosts() {
      this.loading = true
      axios.get('/tjgwk/gettjgwk', {params: {YHM: this.UserInfo.username, YHSFDM: 4}})
          .then(res => {
            console.log('接口返回', res.data)
            const data = res.data.data
            this.allData = Array.isArray(data) ? data : (data.records || [])
          })
          .catch(err => console.error('请求失败', err))
          .finally(() => {
            this.loading = false
            this.currentPage = 1
          })
    },
    applyFilters() {
      this.currentPage = 1
    },
    resetFilters() {
      this.filterParams = {GWMC: '', TJSJ: [], TJR: '', SFTJ: false}
      this.applyFilters()
    },
    handlePageChange(page) {
      this.currentPage = page
    },
    refreshData() {
      this.getLoginUserInfo()
    },
    contactCompany() {
      this.$message.info('联系方式功能待实现')
    }
  },
  mounted() {
    this.getLoginUserInfo()
  }
}
</script>

<style scoped>
.expand-content p {
  margin-bottom: 0.5rem;
}

.mb-6 {
  margin-bottom: 1.5rem !important;
}
</style>
